<template>
    <div class="page-wrapper">
        <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
            <el-form-item>
                <el-button type="primary" @click="addOrUpdateHandle({})" v-if="hasRule('admin/inventory/purchase/index/add')">新建采购单</el-button>
            </el-form-item>
            <el-form-item>
                <el-date-picker :shortcuts="SHORTCUTS" v-model="record_time" style="width:240px;" @change="dataChange" type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" clearable />
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.contents" placeholder="输入产品名称搜索" clearable style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select
                    v-model="state.queryForm.type"
                    clearable
                    placeholder="选择采购类型"
                    style="width: 150px"
                >
                    <el-option label="产品采购" :value="1" />
                    <el-option label="材料采购" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.batch_no" placeholder="输入批次号搜索" clearable style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.supplier_name" placeholder="输入供应商搜索" clearable style="width: 150px"></el-input>
            </el-form-item>
            <!-- <el-form-item>
                <el-input v-model="state.queryForm.company_manager" placeholder="归属人" clearable style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="state.queryForm.submitter" placeholder="提交人" clearable style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select v-model="state.queryForm.checked" value-key="" placeholder="状态" clearable style="width: 150px">
                    <el-option label="待审核" value="3"></el-option>
                    <el-option label="已确认" value="4"></el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item>
                <el-button @click="getDataList()" type="primary">查询</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </el-form-item>
        </el-form>
			<!-- <div>
				<el-button type="primary" v-if="hasRule('admin/inventory/purchase/index/add')" @click="handleExport" :loading="loading">导出</el-button>
			</div> -->
		<el-table v-loading="state.dataListLoading" :data="dataList" border style="width: 100%" width="100%" height="100%" @selection-change="selectionChangeHandle" @row-dblclick="rowDblclick">
			<!-- <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column> -->
			<!-- <el-table-column prop="id" label="单号" header-align="center" align="center"></el-table-column> -->
			<el-table-column prop="order_sn" label="采购单号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="batch_no" label="批次号" header-align="center" align="center"></el-table-column>
			<!-- <el-table-column prop="status" label="采购类型" header-align="center" align="center">
				<template #default="scope">
					<span v-if="scope.row.is_fee == 3" class="status2">退款审核中</span>
					<span v-if="scope.row.is_fee == 4" class="status3">已退款</span>
				</template>
			</el-table-column> -->
			<el-table-column prop="time" label="采购时间" header-align="center" align="center"></el-table-column>
			<el-table-column prop="type" label="采购类型" header-align="center" align="center">
                <template #default="scope">
					<span v-if="scope.row.type == 1">产品采购</span>
					<span v-if="scope.row.type == 2">材料采购</span>
				</template>
            </el-table-column>
			<el-table-column prop="status" label="采购状态" header-align="center" align="center">
                <template #default="scope">
					<span v-if="scope.row.status == 1" class="status2">草稿</span>
					<span v-if="scope.row.status == 2" class="status4">生产中</span>
					<span v-if="scope.row.status == 3" class="status3">已完成</span>
				</template>
            </el-table-column>
			<el-table-column prop="detail" label="采购产品" header-align="center" align="center" width="150">
                <template #default="scope">
                    <el-tooltip
                        placement="top"
                        :content="scope.row.detailInfo"
                        raw-content
                    >
                        <div class="w100 text-cut">
                            <span v-if="scope.row.detail?.length">{{ scope.row.detail[0].productName }}</span>
                        </div>
                    </el-tooltip>
                    <!-- <div class="w100" v-if="scope.row.detail.length == 1">
                        {{ scope.row.detail[0].product_name }}({{ scope.row.detail[0].product_attr }})，采购数量：{{ scope.row.detail[0].quantity }}
                    </div> -->
					<!-- <span v-for="item,i in scope.row.detail" :key="i">{{ item.product_name }}{{ i != scope.row.detail.length-1 ? '、' : '' }}</span> -->
				</template>
            </el-table-column>
			<el-table-column prop="supplier_name" label="供应商名称" header-align="center" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="remark" label="采购备注" header-align="center" align="center" show-overflow-tooltip width="100"></el-table-column>
			<el-table-column prop="operator" label="最后操作人" header-align="center" align="center"></el-table-column>
			<el-table-column prop="updated_at" label="最后修改时间" header-align="center" align="center"></el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
				<template #default="scope">
					<el-button type="primary" link @click="addOrUpdateHandle(scope.row, true)" v-if="hasRule('admin/inventory/purchase/index/detail')">查看</el-button>
					<el-button type="primary" link @click="addOrUpdateHandle(scope.row)" v-if="hasRule('admin/inventory/purchase/index/update') && (scope.row.status == 1||scope.row.status == 2)">编辑</el-button>
					<el-button type="danger" link @click="deleteHandle(scope.row.id)" v-if="hasRule('admin/inventory/purchase/index/delete') && scope.row.status == 1">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.per_page"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
	</div>
</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref, computed } from 'vue'
import store from '@/store'
import { IHooksOptions } from '@/hooks/interface'
import { ElMessageBox, ElMessage } from 'element-plus'
import { hasRule, downMethod, timeResetDate } from '@/utils/tool'
import { postApi, addPurchase } from '@/api/api'
import { SHORTCUTS } from '@/config'
import AddOrUpdate from './add-or-update.vue'
import { elMsg } from '@/utils/message';

const prop = defineProps({
	scrollTop:{
		type: Number,
		default: 0
	}
})
const emit = defineEmits(['setScroll'])
let scrollTopData = 0;
const state: IHooksOptions = reactive({
	dataListUrl: '/api/strator/purchase/list',
	deleteUrl: '/api/strator/purchase/delete',
	queryForm: {
		batch_no: '',
		supplier_name: '',
		contents: '',
		type: '',
		start: '',
		end: '',
	}
})
const record_time = ref([])
// 选择时间范围
const dataChange = (e: any) => {
	if(e){
		state.queryForm.start = e[0] + ' 00:00:00'
		state.queryForm.end = e[1] + ' 23:59:59'
	}else{
		state.queryForm.start = ''
		state.queryForm.end = ''
	}
}
const addOrUpdateRef = ref()
const dataList = computed(() => {
	state.dataList?.forEach((item: any) => {
        if (item.contents) {
            item.contents = JSON.parse(item.contents);
            if(item.contents.length && item.contents[0].productName){
                item.detail = item.contents;
            }else{
                item.detail = [];
            }
		}else{
            item.detail = [];
        }
        item.detailInfo = "";
        if (item.detail?.length) {
            let toa = 0;
            item.detail.forEach(tem => {
                toa += Number(tem.quantity)
                item.detailInfo += `
                    <div class="flex flexB"><span class="mr20">${tem.productName}(${tem.product_attr})</span><span style="width: 100px">采购数量：${tem.quantity}</span></div>
                `
            })
            item.detailInfo += `<div style="text-align: right">采购总数：${Number((toa).toFixed(2))}</div>`
        }
	})
	return state.dataList
})
const addOrUpdateHandle = (row: any, isView?: any) => {
	addOrUpdateRef.value.init(row.id,1, isView, row.status)
}
const loading = ref(false)
const handleExport = () => {
	let data = {
		...state.queryForm,
		export: '1'
	}
	let ajaxData: any = {
		params:data,
		method:'POST',
		url:'/api/shop/in_store/list',
		fileType:'xlsx',
		fileName:'采购单' + timeResetDate()
	}
	loading.value = true
	downMethod(ajaxData).then((res: any) => {
		loading.value = false
		if(res){
			ElMessage.success({
				message: '导出成功',
				duration: 1500,
			})
		} else {
			ElMessage.error('导出失败，请重试')
		}
	}).catch((err: any) => {
		loading.value = false
		ElMessage.error('导出失败，请重试')
		// .console.log(err)
	})
}
const handleDel = (id: number) => {
	ElMessageBox.confirm('确认删除吗？', '操作提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		closeOnClickModal: false,
		customClass: 'receiptConfirm',
		center: true
	})
		.then(({ value }) => {
			postApi('/api/shop/in_store/delete', {
				id:id,
			}).then((res: any) => {
				if(res.code == 200){
					ElMessage.success({
						message: '删除成功',
						duration: 1200,
					})
					getDataList()
				} else {
					ElMessage.error(res.message || res.data || '操作失败，请重试')
				}
			}).catch((err: any) => {
				// .console.log(err)
			})
		})
		.catch(() => {})
}
const resetForm = () => {
	record_time.value = []
	state.queryForm.batch_no = ''
	state.queryForm.supplier_name = ''
	state.queryForm.contents = ''
	state.queryForm.type = ''
	state.queryForm.start = ''
	state.queryForm.end = ''
	getDataList()
}
const rowDblclick = (row,col) => {
    if(col.property == 'remark'){
        ElMessageBox.prompt('请输入备注', '修改备注', {
            confirmButtonText: '提交',
            cancelButtonText: '关闭',
            inputValue: row.remark
        })
            .then(({ value }) => {
                addPurchase({
                    id: row.id,
                    remark: value
                }).then((result) => {
                    elMsg('已提交', 'success')
                    currentChangeHandle(state.page)
                }).catch((err) => {
                    
                });
            })
            .catch(() => {
            // .
        })
    }
}
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteHandle } = useCrud(state)
</script>
<style lang="scss" scoped>
.receivable {
	:deep() {
		.el-tabs__header {
			margin: 0 0 5px;
		}
	}
}
</style>
